<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Package\Attendance\Days;
use App\Models\Attendance\Holiday;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Builder;

/**
 * 假期逻辑控制器
 *
 * Date: 2018/5/29
 * @author George
 * @package App\Http\Controllers
 */
class HolidayController extends Controller
{
	/**
	 * 获取企业的节假日列表
	 *
	 * Date: 2018/5/29
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function index(Request $request)
	{
		$user = Auth::user();
		$description = $request->get('description');
		$paginate = $request->get('paginate', 15);
		$query = Holiday::query()->where('company_id', $user->company_id);

		$query->when($description, function ($query, $description) {
			/**
			 * @var Builder $query
			 */
			$query->where('description', 'like', "%{$description}%");
		});

		return success($query->paginate($paginate));
	}

	/**
	 * 获取节假日详情
	 *
	 * Date: 2018/5/29
	 * @author George
	 * @param Holiday $holiday
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function show(Holiday $holiday)
	{
		return success($holiday);
	}

	/**
	 * 创建节假日
	 *
	 * Date: 2018/5/29
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function store(Request $request)
	{
		$user = Auth::user();
		$attributes = $this->validate($request, [
			'description' => 'required',
			'start' => 'required|date',
			'end' => 'required|date',
			'type' => ['required', Rule::in(['法定', '自定'])],
		]);

		$dates = Days::all($attributes['start'], $attributes['end']);

		$attributes['company_id'] = $user->company_id;
		$attributes['days'] = $dates->days;

		$holiday = Holiday::create($attributes);
		return stored($holiday);
	}

	/**
	 * 更新节假日
	 *
	 * Date: 2018/5/29
	 * @author George
	 * @param Request $request
	 * @param Holiday $holiday
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function update(Request $request, Holiday $holiday)
	{
		$attributes = $this->validate($request, [
			'description' => 'required',
			'start' => 'required|date',
			'end' => 'required|date',
			'type' => ['required', Rule::in(['法定', '自定'])]
		]);

		$dates = Days::all($attributes['start'], $attributes['end']);
		$attributes['days'] = $dates->days;

		$holiday->update($attributes);
		return updated($holiday);
	}

	/**
	 * 删除节假日
	 *
	 * Date: 2018/5/29
	 * @author George
	 * @param Holiday $holiday
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Exception
	 */
	public function destroy(Holiday $holiday)
	{
		$holiday->delete();
		return deleted();
	}
}
